"""
Timeout feature from stackoverflow.
usage:
    try:
        with timeout ( seconds=5 ):
            # Do some thing
    except Exception, e:
        #hadnle run time exception for timeout
"""
import signal


class timeout:
    def __init__(self, seconds=1, error_message='Timeout'):
        self.seconds = seconds
        self.error_message = error_message

    def handle_timeout(self, signum, frame):
        raise RuntimeError ( self.error_message )

    def __enter__(self):
        signal.signal ( signal.SIGALRM, self.handle_timeout )
        signal.alarm ( self.seconds )

    def __exit__(self, type, value, traceback):
        signal.alarm ( 0 )
